<?php
/**
 * Created by PhpStorm
 * User: honglin
 * Date: 2022/9/5
 * Time: 下午4:05
 */

namespace App\Library\User;

class UserInvitationCode
{
    /**
     * @var null
     */
    private $value;

    public function __construct($value = null)
    {
        $this->value = $value;
    }

    /**
     * 解析
     * @return
     */
    public function encrypt(){
        $format = 8;
        $to = 36;
        $dictArr = array("0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D","E", "F", "G", "H", "I", "J", "K", "L","M", "N", "O","P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y","Z");
        $asciiArr = array();
        $loop = true;
        while ($loop) {
            $asciiArr[] = $dictArr[bcmod($this->num, $to)];
            $num = floor(bcdiv($this->num, $to));
            if ($num == 0) {
                $loop = false;
            }
        }
        $asciiArr = array_pad($asciiArr, $format, $dictArr[0]); //这一步可有可无，根据自己需求走
        $asciiStr = implode('', array_reverse($asciiArr));
        return $asciiStr;
    }

    public function decode(){
        $from = 36;
        $dictArr = array("0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D","E", "F", "G", "H", "I", "J", "K", "L","M", "N", "O","P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y","Z");
        $dict = array_flip($dictArr);
        $str = ltrim($this->value, $dictArr[0]);
        $length = strlen($str);
        $str = str_split(strrev($str));
        $num = 0;
        for ($i = 0, $j = $length; $i < $j; $i++) {
            $num = bcadd(bcmul($dict[$str[$i]], bcpow($from, $i)), $num);
        }
        return $num;
    }

    public static function init($value){
        return new static($value);
    }
}